#!/usr/bin/env python3
#
# Core script for Weathercomp.

import importlib
import logging
import os
import sqlite3
import sys

import forecasts
import report

def storeforecast(forecast, source, locid, con):
    query = 'INSERT INTO Forecast \
            (LocID, Source, ObservationDate, ForecastDate, TempMin, TempMax) \
            VALUES (:locid, :source, :obsdate, :fordate, :min, :max);'
    con.execute(query, 
        {
        'locid': locid,
        'source': source,
        'obsdate': forecast.date_observed.isoformat(),
        'fordate': forecast.date_forecasted.isoformat(),
        'min': forecast.t_min,
        'max': forecast.t_max
        })
    logging.info('{place}, {source}, {now}, {then}, {min}, {max}'.format(
        place=locid,
        source=source,
        now=forecast.date_observed,
        then=forecast.date_forecasted,
        min=forecast.t_min,
        max=forecast.t_max))

def storereport(report, locid, con):
    query = 'INSERT INTO Report (Date, LocID, TempMin, TempMax)\
VALUES (:date, :locid, :min, :max);'
    con.execute(query,
        {
        'date': report.date_observed.isoformat(),
        'locid': locid,
        'min': report.t_min,
        'max': report.t_max
        })
    logging.info('{date}, {place}, {min}, {max}'.format(
        date=report.date_observed.isoformat(),
        place=locid,
        min=report.t_min,
        max=report.t_max))

def get_forecasts(con):
    logging.info('Fetching and storing forecasts...')
    fcs = []
    for modname in forecasts.modules:
        print('Using module: {0}'.format(modname))
        module = importlib.import_module('forecasts.' + modname)
        fcs.append(module.ForecastGen)

    query = 'SELECT LocID, Name, Latitude, Longitude FROM Location;'
    # fetchall because looping over the cursor did stupid things.
    locations = con.execute(query).fetchall()
    for location in locations:
        print(location['Name'])
        for ForecastGen in fcs:
            gen = ForecastGen(location['Latitude'], location['Longitude'])
            for daysahead in [1,2,4]:
                storeforecast(
                    gen.getforecast(daysahead), 
                    gen.shortname, location['LocID'], con)
    con.commit()

def get_reports(con):
    logging.info('Fetching and storing reports...')
    reportgen = report.ReportGen()
    query = 'SELECT LocID, Name, Latitude, Longitude FROM Location;'
    locations = con.execute(query).fetchall()
    for location in locations:
        logging.info(location['Name'])
        storereport(
            reportgen.getreport(location['Latitude'], location['Longitude']), 
            location['LocID'], con)
    con.commit()

if __name__ == "__main__":
    logging.basicConfig(format='%(levelname)s-%(name)s: %(message)s', level=logging.INFO)
    os.chdir(sys.path[0])
    con = sqlite3.connect('weathercomp.db')
    con.execute('PRAGMA foreign_keys = on;')
    con.row_factory = sqlite3.Row

    get_forecasts(con)
    get_reports(con)

    con.close()
